#include "Gray_Sensor.h"
float gw_offset = 0.0;
uint8_t is_in_angle = 0;
unsigned char Digtal;
unsigned char rx_buff[256]={0};
uint8_t sensor_buffer[9] = {0, 0, 0, 0, 0, 0, 0,0,0}; 

uint8_t gw_gray_serial_read()
{
	uint8_t ret = 0;
	uint8_t i;

	for (i = 0; i < 8; ++i) {
		/* 输出时钟下降沿 */
		DL_GPIO_clearPins(GW_GRAY_PORT, GW_GRAY_CLK_PIN);
		delay_us(2);
		//避免GPIO翻转过快导致反应不及时
		ret |= (DL_GPIO_readPins(GW_GRAY_PORT, GW_GRAY_DAT_PIN)==0?0:1) << i;

		/* 输出时钟上升沿,让传感器更新数据*/
		DL_GPIO_setPins(GW_GRAY_PORT, GW_GRAY_CLK_PIN);
	
		/* 延迟需要在5us左右 */
		delay_us(5);
	}
	//uart0_printf("%d\n ",ret);
	 SEP_ALL_BIT8(ret,sensor_buffer[1], sensor_buffer[2], sensor_buffer[3], sensor_buffer[4],
				 sensor_buffer[5], sensor_buffer[6], sensor_buffer[7], sensor_buffer[8]);
	return ret;
	
}
float cal_sensor_offset(void)
{
	float offset = 0.0;
	int8_t sum = 0;
	for (int i = 1; i <= 8; i++)
	{
		sum += sensor_buffer[i];
	}
	if ((8-sum) == 2) //检测到相邻2个传感器在黑线上
	{
		for (int i = 1; i <= 8; i++)
		{
			if (sensor_buffer[i] == 0 && sensor_buffer[i + 1] == 0)
			{
				offset = i - 4; // 计算偏移量
				break;
			}
		}
	}
	else if ((8-sum) >= 3) // 检测到3个及以上传感器在黑线上
	{
		for (uint8_t i = 2;i<=7;i++)
		{
			if (sensor_buffer[i] == 0 && sensor_buffer[i + 1] == 0 && sensor_buffer[i - 1] == 0)
			{
				offset = i - 4.5; // 计算偏移量
				break;
			}
		}

	}
	else if ((8-sum) == 1) // 只检测到1个传感器在黑线上
	{
		for (int i = 1; i <= 8; i++)
		{
			if (sensor_buffer[i] == 0)
			{
				offset = i - 4.5; // 计算偏移量
				break;
			}
		}
	}
	else // 没有检测到黑线
	{
		offset = 0; // 偏移量为0
	}
	return offset; // 返回偏移量
}

void GW_proc(void)
{
		gw_gray_serial_read();
		gw_offset = cal_sensor_offset(); // 计算偏移量
		//uart0_printf("Digtal 	%d-%d-%d-%d-%d-%d-%d-%d\r\n",sensor_buffer[1], sensor_buffer[2], sensor_buffer[3], sensor_buffer[4],
				 //sensor_buffer[5], sensor_buffer[6], sensor_buffer[7], sensor_buffer[8]);

}



uint8_t GW_Check_Sum(void)
{
	uint8_t sum = 0;
	for (int i = 1; i <= 8; i++)
	{
		sum += sensor_buffer[i];
	}
	return 8-sum;
}